package com.LCQ.crm.settings.web.controller;

import com.LCQ.crm.exception.LoginException;
import com.LCQ.crm.settings.domain.User;
import com.LCQ.crm.settings.service.UserService;
import com.LCQ.crm.settings.service.UserServiceImpl;
import com.LCQ.crm.utils.PrintJson;
import com.LCQ.crm.utils.ServiceFactory;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("service");
        String reqUri = request.getRequestURI();

        if(reqUri==null){
            return;
        }

        if(reqUri.contains("login.do")){
            login(request,response);
            return;
        }else if(reqUri.contains("getUserList.do")){
            getUserList(request,response);
            return;
        }
    }

    private void getUserList(HttpServletRequest request, HttpServletResponse response) {
        UserService userService = (UserService) ServiceFactory.getService(new UserServiceImpl());
        List<Map> userMap = userService.selectAll();
        PrintJson.printJsonObj(response,userMap);
    }

    private void login(HttpServletRequest request, HttpServletResponse response) {
        String userName = request.getParameter("userName");
        String password = request.getParameter("password");
        String addr = request.getRemoteAddr();
        System.out.println("addr:" + addr);
        UserService userService = (UserService) ServiceFactory.getService(new UserServiceImpl());

        try {
            User user = userService.login(userName,password,addr);
            request.getSession().setAttribute("user",user);
            PrintJson.printJsonFlag(response,true);
        } catch (LoginException e) {
            e.printStackTrace();
            Map resMap = new HashMap();
            resMap.put("success",false);
            resMap.put("msg",e.getMessage());
            PrintJson.printJsonObj(response,resMap);
        }
    }
}
